package com.jsoup.controller;

import com.jsoup.bean.User;
import com.jsoup.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletRequest request, User user) {

        Map<Object, Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPassword());
        try {
            subject.login(token);
            Session session = subject.getSession();
            User u = new User();
            u.setUserName(user.getUserName());
            User currentUser = userService.getUser(u);
            session.setAttribute("currentUser", currentUser);

            SavedRequest savedRequest = WebUtils.getSavedRequest(request);
            String url = "/";
            if(savedRequest != null){
                url = savedRequest.getRequestUrl();
            }

            map.put("message", "success");
            map.put("url", url);

        } catch (DisabledAccountException e) {
            map.put("message", "该用户未授权");
        } catch (UnknownAccountException e) {
            map.put("message", "该用户不存在");
        } catch (IncorrectCredentialsException e) {
            map.put("message", "密码错误");
        }
        return map;
    }
}
